package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.L1Character;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.templates.WeaponEffect;
import l1j.server.server.utils.SQLUtil;
import l1j.server.server.utils.collections.Lists;
import l1j.server.server.utils.collections.Maps;

public class WeaponEffectTable {
	private static WeaponEffectTable _instance;

	public static WeaponEffectTable getInstance() {
		return _instance;
	}

	public static void initilize() {
		_instance = new WeaponEffectTable();
	}

	private Map<Integer, List<WeaponEffect>> _allEffects = Maps.newMap();

	private WeaponEffectTable() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("SELECT * FROM weapon_effect");

			rs = pstm.executeQuery();
			while (rs.next()) {
				WeaponEffect we = new WeaponEffect(rs.getInt("item_id"),
						rs.getInt("enchant_level_require"),
						rs.getInt("effect_id"),
						rs.getBoolean("effect_arrowtype"), rs.getInt("chance"),
						rs.getInt("dmg_base"), rs.getInt("dmg_random"),
						rs.getInt("rate_str"), rs.getInt("rate_dex"),
						rs.getInt("rate_int"), rs.getInt("rate_con"),
						rs.getInt("rate_wis"), rs.getInt("rate_cha"),
						rs.getInt("attr"), rs.getInt("effect_time"),
						rs.getInt("effect_delay"), rs.getInt("effect_area"),
						rs.getInt("effect_skill"),
						rs.getInt("effect_skill_time"));
				if (_allEffects.containsKey(we.getItemId())) {
					_allEffects.get(we.getItemId()).add(we);
				} else {
					List<WeaponEffect> list = Lists.newList();
					list.add(we);
					_allEffects.put(we.getItemId(), list);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public void effect(int itemId, int enchant_level, L1PcInstance pc,
			L1Character cha) {
		if (_allEffects.containsKey(itemId)) {
			List<WeaponEffect> list = _allEffects.get(itemId);
			WeaponEffect we = list.get(0);
			for (int i = 0; i < list.size(); i++) {
				if (enchant_level >= list.get(i).getEnchantLevelRequire()) {
					if (list.get(i).getEnchantLevelRequire() >= we
							.getEnchantLevelRequire()) {
						we = list.get(i);
					}
				}
			}
			if (enchant_level >= we.getEnchantLevelRequire()) {
				we.effect(pc, cha);
			}
		}
	}
}
